package com.dpl.yyrj.ui.adapter;


import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;

import com.dpl.base.BaseDialog;
import com.dpl.yyrj.R;
import com.dpl.yyrj.app.AppAdapter;
import com.dpl.yyrj.ui.data.DataOfKey;
import com.dpl.yyrj.ui.data.DataOfValue;
import com.dpl.yyrj.ui.data.ItemEdit;
import com.dpl.yyrj.ui.dialog.MenuDialog;
import com.dpl.yyrj.ui.dialog.MessageDialog;
import com.dpl.yyrj.ui.dialog.TimeDialog;
import com.dpl.yyrj.utils.JsonUtil;
import com.dpl.yyrj.utils.LogUtil;
import com.dpl.yyrj.utils.MMKVUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author dpl
 * @date: 2025/8/2 星期六 20:09
 * @description 填数据item
 **/
public class AddDataAdapter extends AppAdapter<ItemEdit> {
    private static final String TAG = "AddDataAdapter";
    private Date date = new Date(System.currentTimeMillis());

    public AddDataAdapter(Context context) {
        super(context);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder();
    }

    /**
     * 默认获取编辑的日期，若需要获取其他日期，请调用setDate方法
     */
    public void setDate(Date date) {
        this.date = date;
    }

    public String getCurrentJson() {
        String type = getData().get(0).getType();
        String mmkv_key = getMmkvKey(type);
        LogUtil.i(TAG, "getCurrentJson: " + mmkv_key);
        // 查询当日数据是否已存在
        String currentJson = JsonUtil.getJsonArrayByMMKVKey(mmkv_key);
        return currentJson;
    }

    private final class ViewHolder extends AppAdapter<?>.ViewHolder {

        private AppCompatTextView tv_content_value;
        private AppCompatTextView tv_content_time;
        private ImageView img_del;

        private ViewHolder() {
            super(R.layout.item_element_eidt);
            initView();
        }

        @Override
        public void onBindView(int position) {
            //展示数据
            ItemEdit item = getItem(position);
            tv_content_value.setText(item.getValue());
            tv_content_time.setText(item.getTime());
            int currentPosition = position;
            img_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new MessageDialog.Builder(getContext())
                            // 标题可以不用填写
                            .setTitle("提示")
                            // 内容必须要填写
                            .setMessage("是否删除？")
                            // 确定按钮文本
                            .setConfirm(getString(R.string.common_confirm))
                            // 设置 null 表示不显示取消按钮
                            .setCancel(getString(R.string.common_cancel))
                            // 设置点击按钮后不关闭对话框
                            //.setAutoDismiss(false)
                            .setListener(new MessageDialog.OnListener() {

                                @Override
                                public void onConfirm(BaseDialog dialog) {
                                    String key = item.getType();
                                    deleteData(key, currentPosition);
                                }

                                @Override
                                public void onCancel(BaseDialog dialog) {

                                }
                            }).show();
                }
            });
            tv_content_time.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 时间选择对话框
                    new TimeDialog.Builder(getContext()).setTitle(getString(R.string.time_title))
                            // 确定按钮文本
                            .setConfirm(getString(R.string.common_confirm))
                            // 设置 null 表示不显示取消按钮
                            .setCancel(getString(R.string.common_cancel))
                            // 不选择秒数
                            .setIgnoreSecond().setListener(new TimeDialog.OnListener() {

                                @Override
                                public void onSelected(BaseDialog dialog, int hour, int minute, int second) {

                                    // 如果不指定年月日则默认为今天的日期
                                    Calendar calendar = Calendar.getInstance();
                                    calendar.set(Calendar.HOUR_OF_DAY, hour);
                                    calendar.set(Calendar.MINUTE, minute);
                                    calendar.set(Calendar.SECOND, second);
                                    LogUtil.i(TAG, "时间戳：" + calendar.getTimeInMillis());
                                    tv_content_time.setText(new SimpleDateFormat("kk:mm").format(calendar.getTime()));

                                    saveData(item.getType(), tv_content_value.getText().toString(), tv_content_time.getText().toString(), currentPosition);
                                }

                                @Override
                                public void onCancel(BaseDialog dialog) {

                                }
                            }).show();
                }
            });
            tv_content_value.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.getType().equals(DataOfKey.KEY_WEIYANG)) {

                        new MenuDialog.Builder(getContext()).setGravity(Gravity.CENTER)
                                // 设置 null 表示不显示取消按钮
                                //.setCancel(null)
                                // 设置点击按钮后不关闭对话框
                                //.setAutoDismiss(false)
                                .setList(DataOfValue.getWeiyangNailiangList()).setListener(new MenuDialog.OnListener<String>() {

                                    @Override
                                    public void onSelected(BaseDialog dialog, int position, String string) {
                                        tv_content_value.setText(string);
                                        saveData(item.getType(), tv_content_value.getText().toString(), tv_content_time.getText().toString(), currentPosition);
                                    }

                                    @Override
                                    public void onCancel(BaseDialog dialog) {

                                    }
                                }).show();
                    } else if (item.getType().equals(DataOfKey.KEY_SHENGLI)) {
                        new MenuDialog.Builder(getContext()).setGravity(Gravity.CENTER)
                                // 设置 null 表示不显示取消按钮
                                //.setCancel(null)
                                // 设置点击按钮后不关闭对话框
                                //.setAutoDismiss(false)
                                .setList(DataOfValue.getWeiyangNailiangList()).setListener(new MenuDialog.OnListener<String>() {

                                    @Override
                                    public void onSelected(BaseDialog dialog, int position, String string) {
                                        tv_content_value.setText(string);
                                        saveData(item.getType(), tv_content_value.getText().toString(), tv_content_time.getText().toString(), currentPosition);
                                    }

                                    @Override
                                    public void onCancel(BaseDialog dialog) {

                                    }
                                }).show();
                    } else if (item.getType().equals(DataOfKey.KEY_WEILIANGYUANSU)) {
                        new MenuDialog.Builder(getContext()).setGravity(Gravity.CENTER)
                                // 设置 null 表示不显示取消按钮
                                //.setCancel(null)
                                // 设置点击按钮后不关闭对话框
                                //.setAutoDismiss(false)
                                .setList(DataOfValue.getWeiyangNailiangList()).setListener(new MenuDialog.OnListener<String>() {

                                    @Override
                                    public void onSelected(BaseDialog dialog, int position, String string) {
                                        tv_content_value.setText(string);
                                        saveData(item.getType(), tv_content_value.getText().toString(), tv_content_time.getText().toString(), currentPosition);
                                    }

                                    @Override
                                    public void onCancel(BaseDialog dialog) {

                                    }
                                }).show();
                    }

                }
            });
        }

        private void initView() {
            tv_content_value = findViewById(R.id.tv_content_value);
            tv_content_time = findViewById(R.id.tv_content_time);
            img_del = findViewById(R.id.img_delete);
        }
    }

    // TODO: 2025/8/2 删除数据
    private void deleteData(String type, int currentPos) {
        String mmkv_key = getMmkvKey(type);
        String currentJson = JsonUtil.getJsonArrayByMMKVKey(mmkv_key);
        int removeIndex = -1;
        JsonArray jsonArray = JsonUtil.fromJson(currentJson, JsonArray.class);
        boolean contains = false;
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonObject jsonItem = jsonArray.get(i).getAsJsonObject();
            if (jsonItem.get(DataOfKey.KEY_MMKV_DAY_POSITION).getAsInt() == currentPos) {
                removeIndex = i;
            }
        }
        currentJson = JsonUtil.removeArrayElement(currentJson, removeIndex);
        MMKVUtil.putString(mmkv_key, currentJson);
        // adapter 数据处理
        removeItem(currentPos);
        notifyDataSetChanged();
    }

    public String getMmkvKey(String type) {
        String mmkv_key = "";
        if (type.equals(DataOfKey.KEY_WEIYANG)) {
            mmkv_key = DataOfKey.KEY_MMKV_CURRENT_WEIYANG;
        } else if (type.equals(DataOfKey.KEY_SHENGLI)) {
            mmkv_key = DataOfKey.KEY_MMKV_CURRENT_SHENGLI;
        } else if (type.equals(DataOfKey.KEY_WEILIANGYUANSU)) {
            mmkv_key = DataOfKey.KEY_MMKV_CURRENT_WEILIANGYUANSU;
        }
        return mmkv_key;
    }

    // DataOfKey.KEY_WEIYANG KEY_SHENGLI KEY_WEILIANGYUANSU
    private void saveData(String type, String event, String time, int position) {
        String mmkv_key = getMmkvKey(type);
        LogUtil.i(TAG, "saveData: " + type + " " + event + " " + time + " " + position + " " + mmkv_key);
        // 查询当日数据是否已存在
        String currentJson = JsonUtil.getJsonArrayByMMKVKey(mmkv_key);

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty(DataOfKey.KEY_MMKV_EVENT, event);
        jsonObject.addProperty(DataOfKey.KEY_MMKV_TIME, time);
        jsonObject.addProperty(DataOfKey.KEY_MMKV_DAY_POSITION, position);
        jsonObject.addProperty(DataOfKey.KEY_MMKV_DAY, getDateString());


        // 若存在则更新  不存在则添加 插入数据
        if (currentJson.equals("[]")) {
            currentJson = JsonUtil.insertArrayElement(currentJson, jsonObject);
        } else {
            JsonArray jsonArray = JsonUtil.fromJson(currentJson, JsonArray.class);
            boolean contains = false;
            for (int i = 0; i < jsonArray.size(); i++) {
                JsonObject jsonObject1 = jsonArray.get(i).getAsJsonObject();
                if (jsonObject1.get(DataOfKey.KEY_MMKV_DAY_POSITION).getAsInt() == position) {
                    contains = true;
                }
            }
            if (contains) {
                currentJson = JsonUtil.upDateArrayElement(currentJson, jsonObject, position);
            } else {
                currentJson = JsonUtil.insertArrayElement(currentJson, jsonObject);
            }

        }
        LogUtil.i(TAG, mmkv_key + "currentjson :" + currentJson);
        MMKVUtil.putString(mmkv_key, currentJson);
        LogUtil.i(TAG, "currentJson2 :" + MMKVUtil.getString(mmkv_key, ""));

    }

    public String getDateString() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(date);
    }


}
